'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

exports.default = removeOne;

var _helpers = require('./helpers');

var _findOne = require('./findOne');

var _findOne2 = _interopRequireDefault(_findOne);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/* eslint-disable no-param-reassign */

function removeOne(model, tc, opts) {
  if (!model || !model.modelName || !model.schema) {
    throw new Error('First arg for Resolver removeOne() should be instance of Mongoose Model.');
  }

  if (!tc || tc.constructor.name !== 'TypeComposer') {
    throw new Error('Second arg for Resolver removeOne() should be instance of TypeComposer.');
  }

  const findOneResolver = (0, _findOne2.default)(model, tc, opts);

  const outputTypeName = `RemoveOne${tc.getTypeName()}Payload`;
  const outputType = tc.constructor.schemaComposer.getOrCreateTC(outputTypeName, t => {
    t.addFields({
      recordId: {
        type: 'MongoID',
        description: 'Removed document ID'
      },
      record: {
        type: tc,
        description: 'Removed document'
      }
    });
  });

  const resolver = new tc.constructor.schemaComposer.Resolver({
    name: 'removeOne',
    kind: 'mutation',
    description: 'Remove one document: ' + '1) Remove with hooks via findOneAndRemove. ' + '2) Return removed document.',
    type: outputType,
    args: (0, _extends3.default)({}, (0, _helpers.filterHelperArgs)(tc, model, (0, _extends3.default)({
      filterTypeName: `FilterRemoveOne${tc.getTypeName()}Input`,
      model
    }, opts && opts.filter)), (0, _helpers.sortHelperArgs)(tc, model, (0, _extends3.default)({
      sortTypeName: `SortRemoveOne${tc.getTypeName()}Input`
    }, opts && opts.sort))),
    resolve: (() => {
      var _ref = (0, _asyncToGenerator3.default)(function* (resolveParams) {
        const filterData = resolveParams.args && resolveParams.args.filter || {};

        if (!(typeof filterData === 'object') || Object.keys(filterData).length === 0) {
          return Promise.reject(new Error(`${tc.getTypeName()}.removeOne resolver requires at least one value in args.filter`));
        }

        // We should get all data for document, cause Mongoose model may have hooks/middlewares
        // which required some fields which not in graphql projection
        // So empty projection returns all fields.
        resolveParams.projection = {};

        let doc = yield findOneResolver.resolve(resolveParams);

        if (resolveParams.beforeRecordMutate) {
          doc = yield resolveParams.beforeRecordMutate(doc, resolveParams);
        }

        if (doc) {
          yield doc.remove();

          return {
            record: doc,
            recordId: tc.getRecordIdFn()(doc)
          };
        }

        return null;
      });

      return function resolve(_x) {
        return _ref.apply(this, arguments);
      };
    })()
  });

  return resolver;
}